import { defineConfig, loadEnv } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
import { buildTimePlugin } from './vitePlugins';

import path from 'path';
import fs from 'fs';
import { format } from 'prettier';

const basePath = path.resolve(__dirname, './');
const srcPath = path.resolve(__dirname, './src/');

// tailwind参考
// https://zhuanlan.zhihu.com/p/515048219?utm_id=0
// https://github.com/sonofmagic/weapp-tailwindcss/tree/main/demo/uni-app-vue3-vite
const {
  UnifiedViteWeappTailwindcssPlugin: vwt,
} = require('weapp-tailwindcss-webpack-plugin/vite');
// 注意： 打包成 h5 和 app 都不需要开启插件配置
const isH5 = process.env.UNI_PLATFORM === 'h5';
const isApp = process.env.UNI_PLATFORM === 'app-plus';
const WeappTailwindcssDisabled = isH5 || isApp;
// vite 插件配置
const vitePlugins = [
  uni(),
]; // Unocss()
// postcss 插件配置
const postcssPlugins = [require('autoprefixer')(), require('tailwindcss')()];

// const postcssPlugins = [require('postcss-windicss')()];

// const postcssPlugins = [];
if (!WeappTailwindcssDisabled) {
  let start;
  vitePlugins.push(
    vwt({
      wxsMatcher() {
        return false;
      },
      inlineWxs: true,
      jsEscapeStrategy: 'replace', // 'regenerate'
      onStart() {
        start = performance.now();
      },
      onEnd() {
        console.log(
          'UnifiedWebpackPluginV5 onEnd:',
          performance.now() - start,
          'ms',
        );
      },
      // appType: 'uni-app'
      // customReplaceDictionary: {
      //   '[': '_',
      //   ']': '_',
      //   '(': '_',
      //   ')': '-',
      // },
    }),
  );

  postcssPlugins.push(
    require('postcss-rem-to-responsive-pixel')({
      rootValue: 32,
      propList: ['*'],
      transformUnit: 'rpx',
    }),
  );
  postcssPlugins.push(
    require('weapp-tailwindcss-webpack-plugin/css-macro/postcss'),
  );
}

// https://vitejs.dev/config/
export default defineConfig(async ({ command, mode, ssrBuild }) => {
  const env = loadEnv(mode, process.cwd());

  const configSrc = path.resolve(__dirname, './src/project.config.json');
  const projectConfig = fs.readFileSync(configSrc);
  const json = JSON.parse(projectConfig);
  json.appid = env.VITE_APPID;
  const formatStr = await format(JSON.stringify(json), {
    semi: false,
    parser: 'json',
  });
  fs.writeFileSync(configSrc, formatStr);

  return {
    plugins: [...vitePlugins, buildTimePlugin(mode)],
    css: {
      postcss: {
        plugins: postcssPlugins,
      },
    },
    build: {
      minify: false,
      sourcemap: false,
      rollupOptions: {
        external: [/tailwind.config/g],
      },
    },
    resolve: {
      alias: {
        '@': srcPath,
        '~': basePath,
        // axios引用问题
        'axios/lib/core/settle': path.resolve(
          __dirname,
          './node_modules/axios/lib/core/settle.js',
        ),
        'axios/lib/helpers/buildURL': path.resolve(
          __dirname,
          './node_modules/axios/lib/helpers/buildURL.js',
        ),
        'axios/lib/core/buildFullPath': path.resolve(
          __dirname,
          './node_modules/axios/lib/core/buildFullPath.js',
        ),
      },
    },
  };
});
